<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Node(value) {
            this.val = value;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(6)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        var levelOrder = function (root) {
            const res = []
            // 调用递归函数
            set(root, 0, res)
            return res
        };

        /* 
          时间复杂度：O(n) 表示递归的节点
          空间复杂度：O(n) 结果数组的长度最多是n
        */
        function set(node, level, res) {
            // 退出条件
            if (!node) {
                return
            }

            // 每层要执行的内容
            if (res[level]) {
                // 值放到对应层级的数组里面去
                res[level].push(node.val)
            }  else {
                // 该层的第一个数，先创建一个数组
                res[level] = [node.val]
            }

            // 递归传递的参数
            set(node.left, level + 1, res)
            set(node.right, level + 1, res)
        }
        console.log(levelOrder(a));
    </script>
</body>

</html>